# app/models/message.py
from app import db
from datetime import datetime
from sqlalchemy import Enum

class Message(db.Model):
    __tablename__ = 'messages'

    message_id = db.Column(db.String(36), primary_key=True)
    channel_id = db.Column(db.String(36), db.ForeignKey('channels.channel_id'))
    direct_chat_id = db.Column(db.String(36), db.ForeignKey('direct_chats.chat_id'))
    sender_id = db.Column(db.String(36), db.ForeignKey('users.user_id'), nullable=False)
    content = db.Column(db.JSON, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    channel = db.relationship('Channel', back_populates='messages')
    direct_chat = db.relationship('DirectChat', back_populates='messages')
    sender = db.relationship('User', back_populates='messages_sent')

    # 确保消息必须属于频道或私聊中的一种
    __table_args__ = (
        db.CheckConstraint(
            '(channel_id IS NOT NULL AND direct_chat_id IS NULL) OR '
            '(channel_id IS NULL AND direct_chat_id IS NOT NULL)',
            name='chk_message_source'
        ),
    )

    def __repr__(self):
        return f'<Message {self.message_id[:8]} by {self.sender.username}>'